package ru.urfc.portal.dao.filter;

import java.util.ArrayList;
import java.util.List;

import ru.urfc.portal.dao.Paging;
import ru.urfc.portal.ui.client.Constants;

public class Filter implements Constants {
	public static final Filter NULL = new Filter();
	
	private Paging paging = Paging.NULL_OBJECT;
	private List<String> fetches = new ArrayList<String>(); 
	
	private List<Predicate> predicates = new ArrayList<Predicate>();

	public Filter() {
	}
	
	public Filter(Filter filter) {
		predicates.addAll(filter.predicates);
	}

	public Filter(String propertyName, Object value) {
		this(propertyName, Operator.EQUAL, value);
	}

	public Filter(String propertyName, Operator operator, Object value) {
		add(propertyName, operator, value);
	}

	public Filter add(String propertyName, Operator operator, Object value) {
		if (value != null) {
			predicates.add(new Predicate(propertyName, operator, value));
		}
		return this;
	}

	/**
	 * For unary operations
	 */
	public Filter add(String propertyName, Operator operator) {
		predicates.add(new Predicate(propertyName, operator, null));
		return this;
	}

	public Filter addEqual(String propertyName, Object value) {
		return add(propertyName, Operator.EQUAL, value);
	}
	
	public boolean isNeedWhere() {
		return predicates.size() > 0;
	}

	public String generate(VariablesHolder variablesHolder) {
		StringBuilder where = new StringBuilder();
		for (Predicate predicate: predicates) {
			if (where.length() != 0) {
				where.append(" and ");
			}
			where.append(predicate.generate(variablesHolder));
		}
		return where.toString();
	}
	
	public void setPaging(Integer startIndex, Integer maxResults) {
		paging = new Paging(startIndex, maxResults < 0? 0: maxResults);
	}
	
	public Paging getPaging() {
		return paging;
	}
	
	public void addFetch(String fetch) {
		fetches.add(fetch);
	}

	public String getFetches() {
		String result = "";
		int i = 1;
		for (String fetch: fetches) {
			result += " LEFT JOIN this." + fetch + " f" + i;
		}
		return result;
	}
	
}
